import 'package:flutter/material.dart';
import 'package:enjoy_plus_three/pages/home/index.dart';
import 'package:enjoy_plus_three/pages/mine/index.dart';
import 'package:enjoy_plus_three/utils/event_bus.dart';
import 'package:enjoy_plus_three/utils/logger.dart';
import 'package:enjoy_plus_three/utils/token.dart';

class TabbarPage extends StatefulWidget {
  const TabbarPage({super.key});

  @override
  State<TabbarPage> createState() => _TabbarPageState();
}

class _TabbarPageState extends State<TabbarPage> {
  // 底部tabbar的数据
  List tabBarList = [
    {
      "title": "首页",
      "default": "assets/tabs/home_default.png",
      "active": "assets/tabs/home_active.png"
    },
    {
      "title": "我的",
      "default": "assets/tabs/my_default.png",
      "active": "assets/tabs/my_active.png"
    }
  ];

  // 当前的切换索引
  int currentIndex = 0;

  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var item in tabBarList) {
      items.add(
        BottomNavigationBarItem(
            icon: Image.asset(
              item['default'],
              width: 32,
              height: 32,
            ),
            activeIcon: Image.asset(
              item['active'],
              width: 40,
              height: 40,
            ),
            label: item['title']),
      );
    }
    return items;
  }

  @override
  void initState() {
    super.initState();
    // 需求: "先"初始化仓库之后 Future, "再"需要去做一些其他的事
    // initData();
    // Future.delayed 本质就是创建了Future实例
    // 延迟执行
    // 场景: 执行异步任务, 提供任务完成后的结果(失败 | 成功)
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
      // 去做其他的事
    });

    // 订阅去登录的事件
    eventBus.on<Logout>().listen((event) {
      // ignore: use_build_context_synchronously
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // IndexedStack 实现多个页面之间的切换, 保持状态
      body: SafeArea(
          child: IndexedStack(
        index: currentIndex, // 索引
        children: [HomePage(), MinePage(currentIndex: currentIndex)],
      )),
      bottomNavigationBar: BottomNavigationBar(
        items: barItemList(),
        // type
        type: BottomNavigationBarType.fixed,
        // currentIndex
        currentIndex: currentIndex,
        selectedItemColor: Colors.amber,
        unselectedItemColor: Colors.black,
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }
}
